"""
用于管理用户数据和练习记录
"""
import json
import os
import logging
from typing import Dict, List, Optional
from datetime import datetime

class DataManager:
    def __init__(self):
        self.data_dir = os.path.join("data", "user_data")
        self.ensure_data_directory()
        
    def ensure_data_directory(self) -> None:
        """确保数据目录存在"""
        os.makedirs(self.data_dir, exist_ok=True)
        
    def save_practice_record(self, record: Dict) -> bool:
        """保存练习记录"""
        try:
            file_path = os.path.join(self.data_dir, "practice_records.json")
            records = self.load_practice_records()
            records.append({
                **record,
                "timestamp": datetime.now().isoformat()
            })
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(records, f, ensure_ascii=False, indent=2)
            return True
            
        except Exception as e:
            logging.error(f"保存练习记录失败: {str(e)}")
            return False
            
    def load_practice_records(self) -> List[Dict]:
        """加载练习记录"""
        file_path = os.path.join(self.data_dir, "practice_records.json")
        if not os.path.exists(file_path):
            return []
            
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            logging.error(f"加载练习记录失败: {str(e)}")
            return [] 